package book;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.microedition.io.Connector;
import javax.microedition.io.file.FileConnection;

import com.nokia.mid.impl.isa.ui.DeviceControl;

import files.Files;

public class LightManagerImpl implements LightManager {
	private static final int MIN_LIGHT = 1;
	private static final int MAX_LIGHT = 10;
	private static final int DEFAULT_LIGHT = 5;

	private static String LIGHT_FILE = Files.BOOK_ROOT + "/Light.txt";
	private FileConnection fc;
	private InputStream fis;
	private OutputStream fos;

	private int light;
	
	public LightManagerImpl() throws IOException {
		fc = (FileConnection) Connector.open(LIGHT_FILE);

		if (!fc.exists()) {
			fc.create();
			fos = fc.openOutputStream();
			fos.write(Integer.toString(DEFAULT_LIGHT).getBytes());
			fos.close();
		}
		readLightFromFile();
		applyLight();
	}

	
	private void applyLight() {
		DeviceControl.setLights(0, light * 10);
	}


	private void readLightFromFile() throws IOException {
		byte[] b = new byte[20];
		fis = fc.openInputStream();
		int length = fis.read(b, 0, 20);
		fis.close();
		String raw = new String(b, 0, length);
		light = Integer.parseInt(raw);
	}

	public void decreaseLight() {
		if (light > MIN_LIGHT) {
			light--;
			applyLight();
			try {
				save();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public void increaseLight() {
		if (light < MAX_LIGHT) {
			light++;
			applyLight();
			try {
				save();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	public int getLight() {
		return light;
	}


	private void save() throws IOException {
		fc.delete();
		fc.create();
		fos = fc.openOutputStream();
		fos.write(Integer.toString(light).getBytes());
		fos.close();
	}
}
